package com.mansoor.app.islamicnames.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import static com.mansoor.app.islamicnames.beans.State.get;
import static com.mansoor.app.islamicnames.beans.State.put;
import com.mansoor.app.islamicnames.services.RestClient;
import com.mansoor.app.islamicnames.services.RestClientImpl;
import static com.mansoor.app.islamicnames.util.AppConstant.*;
import org.json.JSONException;

import java.io.IOException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: TKMAQ61
 * Date: Oct 14, 2009
 * Time: 11:30:18 AM
 */
public class NameList extends ListActivity
{

    private RestClient client = new RestClientImpl();
    // private ProgressDialog progressDialog;
    private List<String> names = null;
    private final Handler handler = new Handler()
    {
        public void handleMessage(final Message msg)
        {
            if (names == null || names.size() == 0)
            {
                showDialog(ALERT);
            }
            else
            {
                dismissDialog(PROGRESS);
                // progressDialog.dismiss();
                setListAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, names));
            }

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ServiceThread serviceThread = new ServiceThread();

        //  this.progressDialog = ProgressDialog.show(this, "Fetching", "Names");
        showDialog(PROGRESS);

        serviceThread.start();
        final ListView listView = getListView();
        //  listView.setBackgroundResource(R.drawable.back1);
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        super.onPrepareOptionsMenu(menu);
        MenuItem forward = menu.findItem(R.id.forward);
        MenuItem backward = menu.findItem(R.id.back);//To change body of overridden methods use File | Settings | File Templates.
        Integer pagecount = (Integer) get(PAGE_COUNT);
        Integer currentPage = (Integer) get(CURRENT_PAGE);
        if (currentPage == 1)
        {
            backward.setEnabled(false);
        }
        if (currentPage.equals(pagecount))
        {

            forward.setEnabled(false);
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_menu, menu);

        return true;   //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        switch (id)
        {
            case R.id.forward:
                handleNext();
                return true;
            case R.id.back:
                handlePrevious();
                return true;
            case R.id.search:
                startActivity(new Intent(this, Main.class));
                return true;
        }
        return false;
    }

    private void handleNext()
    {
        Integer currentPage = (Integer) get(CURRENT_PAGE);
        put(CURRENT_PAGE, currentPage + 1);
        put(FIRSTRUN, false);
        Intent intent = new Intent(this, NameList.class);
        startActivity(intent);
    }

    private void handlePrevious()
    {
        Integer currentPage = (Integer) get(CURRENT_PAGE);
        put(CURRENT_PAGE, currentPage - 1);
        put(FIRSTRUN, false);
        Intent intent = new Intent(this, NameList.class);
        startActivity(intent);
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        Dialog dialog = null;
        switch (id)
        {
            case ERROR:
            {
                AlertDialog alertDialog = new AlertDialog.Builder(this).setMessage("Unable to perform request. Please try again later.").setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        startActivity(new Intent(getApplicationContext(), Main.class));
                    }
                }).create();
                dialog = alertDialog;
            }

            case ALERT:
            {
                AlertDialog alertDialog = new AlertDialog.Builder(this).setMessage("No " + get(GENDER) + "  name found for alphabet " + get(ALPHABET)).setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        startActivity(new Intent(getApplicationContext(), Main.class));
                    }
                }).create();

                dialog = alertDialog;

            }

            case PROGRESS:
                ProgressDialog progressDialog = new ProgressDialog(NameList.this);
                // progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setTitle("Fetching");
                progressDialog.setMessage("Names");
                progressDialog.setIndeterminate(true);
                dialog = progressDialog;


        }

        return dialog;

    }

    private List<String> getNames() throws IOException, JSONException
    {

        Integer currentPage = (Integer) get(CURRENT_PAGE);
        String alphabet = (String) get(ALPHABET);
        String gender = (String) get(GENDER);

        Boolean firstRun = (Boolean) get(FIRSTRUN);
        if (firstRun)//firstrun
        {
            currentPage = currentPage + 1;
            put(CURRENT_PAGE, currentPage);
            Integer pageCount = client.count(alphabet, gender);
            put(PAGE_COUNT, pageCount);
        }

        List<String> names = client.getNames(alphabet, gender, currentPage);
        return names;
    }


    @Override
    protected void onListItemClick(ListView listView, View view, int position, long l)
    {
        final String currrntName = names.get(position);
        put(SELECTED_NAME, currrntName);
        Intent intent = new Intent(this, NameDetail.class);
        startActivity(intent);
    }

    private class ServiceThread extends Thread
    {
        @Override
        public void run()
        {
            super.run();    //To change body of overridden methods use File | Settings | File Templates.
            try
            {
                names = getNames();
                handler.sendEmptyMessage(0);
            }
            catch (Exception e)
            {
                dismissDialog(PROGRESS);
                showDialog(ERROR);
            }

        }
    }
}
